package com.skivingcloud.admin.sys.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import com.skivingcloud.admin.sys.entity.SysCaptcha;
import com.skivingcloud.admin.sys.mapper.SysCaptchaMapper;
import com.skivingcloud.admin.sys.service.ISysCaptchaService;
import com.skivingcloud.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 系统验证码 服务实现类
 * </p>
 *
 * @author skivingcloud
 * @since 2022-01-28
 */
@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptcha> implements ISysCaptchaService {

    @Autowired
	private SysCaptchaMapper sysCaptchaMapper;
    
	@Override
	public BufferedImage getCaptcha(String uuid) throws Exception {
		if(StringUtils.isBlank(uuid)){
            throw new Exception("uuid不能为空");
        }
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captchaShear = CaptchaUtil.createCircleCaptcha(120, 40, 4, 20);
        String code = captchaShear.getCode();
        SysCaptcha captcha = new SysCaptcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        //5分钟后过期
        captcha.setExpireTime(LocalDateTime.now().plusMinutes(5l));
        sysCaptchaMapper.insert(captcha);

        return captchaShear.getImage();
	}

	@Override
	public boolean validate(String uuid, String code) {
//		SysCaptcha captchaEntity = sysCaptchaMapper.selectById(uuid);
		SysCaptcha captchaEntity = sysCaptchaMapper.selectOne(new QueryWrapper<SysCaptcha>().eq("uuid", uuid));
      if(captchaEntity == null){
          return false;
      }

      //删除验证码
      sysCaptchaMapper.deleteById(uuid);

      if(captchaEntity.getCode().equalsIgnoreCase(code) && LocalDateTime.now().isBefore(captchaEntity.getExpireTime())){
          return true;
      }

      return false;
	}

}
